from pathlib import Path
import re
from core.detector import BaseOSDetector

class CentOSDetector(BaseOSDetector):
    """CentOS/RHEL 系统检测模块"""
    
    def detect(self) -> bool:
        """检测是否为 CentOS 系发行版"""
        return (
            self._check_release_file() or
            self._check_os_release_id("centos") or
            self._check_os_release_id("rhel")
        )

    def get_version(self) -> str:
        """获取 CentOS/RHEL 主版本号 (如 7/8)"""
        # 方法1: 从 VERSION_ID 获取
        os_release = self.get_os_release()
        if version := os_release.get("VERSION_ID", ""):
            return version.split(".")[0]
        
        # 方法2: 解析发行版文件
        release_file = Path("/etc/redhat-release")
        if release_file.exists():
            match = re.search(r'release (\d+)', release_file.read_text())
            return match.group(1) if match else "unknown"
        
        return "unknown"

    def _check_release_file(self) -> bool:
        """检查是否存在 RedHat 系发行版文件"""
        return any(
            Path(f).exists()
            for f in ["/etc/redhat-release", "/etc/centos-release"]
        )

    def _check_os_release_id(self, target_id: str) -> bool:
        """检查 /etc/os-release 中的发行版 ID"""
        os_release = self.get_os_release()
        return os_release.get("ID", "") == target_id